from collections import defaultdict

class Solution:
    def removeDuplicateLetters(self, s: str) -> str:
        count = defaultdict(int)
        for c in s:
            count[c] += 1

        stack = []
        in_stack = set()

        for c in s:
            count[c] -= 1
            if c in in_stack:
                continue
            while stack and c < stack[-1] and count[stack[-1]] > 0:
                in_stack.remove(stack.pop())
            stack.append(c)
            in_stack.add(c)

        return ''.join(stack)

# 示例用法
if __name__ == "__main__":
    sol = Solution()
    print(sol.removeDuplicateLetters("bcabc"))      # 输出: "abc"
    print(sol.removeDuplicateLetters("cbacdcbc"))   # 输出: "acdb"